import 'package:flutter/material.dart';
import 'package:interview/theme/theme_shared_preference_heiper.dart';
import 'package:interview/utils/logger.dart';


class ThemeProvider extends ChangeNotifier {
  ThemeMode _themeMode = ThemeMode.system; // 默认跟随系统

  ThemeMode get themeMode => _themeMode;

  /// 初始化主题
  Future<void> initializeTheme() async {
    final savedTheme = await ThemeSharedPreferencesHelper.getTheme();
    final newThemeMode = _mapSavedThemeToThemeMode(savedTheme);

    if (_themeMode != newThemeMode) {
      _themeMode = newThemeMode;
      Logger.info("当前主题: $_themeMode", tag: "ThemeProvider");
      notifyListeners(); // 仅当主题变化时通知 UI 更新
    }
  }

  /// 切换主题并通知 UI 更新
  Future<void> switchTheme(String theme) async {
    if (theme != "light" && theme != "dark" && theme != "system") {
      Logger.error("无效的主题设置：$theme", tag: "ThemeProvider");
      return;
    }

    final newThemeMode = _mapSavedThemeToThemeMode(theme);

    if (_themeMode != newThemeMode) {
      _themeMode = newThemeMode;

      // 更新本地存储
      await ThemeSharedPreferencesHelper.updateTheme(theme);

      // 通知所有监听者
      notifyListeners();
    }
  }

  /// 将保存的主题字符串映射到 ThemeMode
  ThemeMode _mapSavedThemeToThemeMode(String savedTheme) {
    switch (savedTheme) {
      case "dark":
        return ThemeMode.dark;
      case "light":
        return ThemeMode.light;
      case "system":
      default:
        return ThemeMode.system;
    }
  }
}
